package com.dfqy.controller;

import com.dfqy.pojo.Admin;
import com.dfqy.service.LoginService;
import com.dfqy.util.PasswordUtil;
import com.dfqy.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class loginController {

    @Value("${server.port}")
    int port;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

        //登陆验证
        @RequestMapping(value = "/login-{name}-{pass}-{vcode}")
            public Result adminLogin(@PathVariable("name") String uName, @PathVariable("pass") String pass, @PathVariable("vcode") String vcode, HttpServletRequest request) {
            System.out.println("登录验证在"+port+"服务器上");
            System.out.println("============================================================");
            System.out.println(uName);
            System.out.println(pass);
            System.out.println(vcode);

            if (!vcode.equals(request.getSession().getAttribute("piccode"))) {
                return Result.error("验证码输入错误");
            }
            Admin admin = loginService.selectAdmin(uName);
            System.out.println(admin+"???????????????????????????????");

            //db
            System.out.println(PasswordUtil.hashPassword(pass));
            System.out.println(PasswordUtil.verifyPassword(pass, admin.getPass()));
            if (admin!=null && PasswordUtil.verifyPassword(pass,admin.getPass())) {
                String key= UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(key,admin,30, TimeUnit.MINUTES);

                //return Result.success(uName,"登录成功");
                return Result.success(key,"登录成功");
            }
            return Result.error("错误的用户名或者密码！");
        }


    //生成验证码图片
    @RequestMapping(value = "/gencode", produces = "application/json;charset=UTF-8")
    public void genCode(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {

        //图像数据缓冲区
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        //绘制图片
        Graphics g = bi.getGraphics();
        //获取颜色
        Color c = new Color(200, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        //生成随机数
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString());
        //输出图片
        //前3个，设置不缓存
        response.setHeader("Prama", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //设置内容类型
        response.setContentType("image/jpeg");

        ImageIO.write(bi, "JPG", response.getOutputStream());
    }
}
